package com.example.demogateway.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class ResponseUtils {
    public static Mono<Void> getResponseTextError(ServerWebExchange exchange, String msg) {
        ServerHttpResponse response = exchange.getResponse();
       String repString = String.format("{\"code\":-1,\"message\",%s}",msg);
        byte[] bits = repString.getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json; charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    public static Mono<Void> getResponseJSONError(ServerWebExchange exchange,int code, String msg) {
        ServerHttpResponse response = exchange.getResponse();
        RestResponse response1 = RestResponse.build(code,msg);
        String repString = JSON.toJSONString(response1);
        byte[] bits = repString.getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json; charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
